<template>
    <BPTable ref='tableRef' align='center' row-key='id' :columns='columns' :api='pageApi' :buttons='buttons'>
        <template #$button>
            <a-button type="primary" ghost @click="openBatch">{{ $c('batch', 'import') }}</a-button>
        </template>
    </BPTable>
    
    <BDialog v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit'>
        <BForm ref='formRef' :label-col='{span : 5}' :fields='formFields'></BForm>
    </BDialog>

    <BDialog v-model:visible='batchVisible' :title='batchDialogTitle' width='600px' :confirm='batchSubmit' @close="closeBatch">
        <a-form layout="vertical">
            <a-form-item required>
                <template #label>
                    {{ $c('import', 'file') }} 
                    <a-tooltip class="m-l-5">
                        <question-circle-outlined />
                        <template #title>{{ $t('maxUpload', [maxBatchCount]) }}</template>
                    </a-tooltip>
                </template>
                <div>
                    <div class="flex">
                        <a-upload :before-upload="beforeUpload" :max-count="1">
                            <a-button>{{ $c('select', 'file') }}</a-button>
                        </a-upload>
                        <span>
                            <a-button type="text" @click="downloadTemplate">{{ $c('download', 'template') }}</a-button>
                        </span>
                    </div>
                </div>
                <div class="m-t-5" v-if="sameCards.length > 0">
                    <a-button type="text" danger @click="downSameCardNos">{{ $c('download', 'same', 'cardNo') }}</a-button>
                </div>
            </a-form-item>
        </a-form>
    </BDialog>

</template>

<script lang='ts' setup>
    import { QuestionCircleOutlined } from '@ant-design/icons-vue';
    import { pageApi, deleteApi, saveApi, saveBatchApi } from '@/api/devices/IotSim'
    import { useI18nStore } from '@/store/i18n'
    import { useResourceStore } from '@/store/resource'
    import { downloadCsv, parseTime, readCsv } from '@/utils'
    import { message, Modal } from 'ant-design-vue'
    import { ref } from 'vue'
    import dayjs from 'dayjs';

    const i18n = useI18nStore()
    const resourceStore = useResourceStore()

    const visible = ref(false)
    const batchVisible = ref(false)

    const tableRef = ref()
    const formRef = ref()
    const dialogTitle = ref()
    const batchDialogTitle = i18n.concat('batch', 'import')

    const file = ref<File>()
    let sameCards = ref<any[]>([])
    const maxBatchCount = 10000

    const formFields:FormField[] = [
        {label : 'id', name : 'id', hidden : true},
        {label : i18n.t('cardNo'), name : 'cardNo', required : true, minlength : 20, maxlength : 20},
        {label : i18n.t('fee'), name : 'fee', type : 'number'},
        {label : i18n.t('expireDate'), name : 'expireIn', type : 'datePicker'}
    ]

    const buttons = ref<SearchButton[]>([])

    if(resourceStore.hasPermission('iotSim:add')) {
        buttons.value.push({
            button : 'add',
            func : () => {
                dialogTitle.value = i18n.t('add')
                formFields.forEach(field => {
                    delete field.defaultValue
                })

                visible.value = true
            }
        })
    }

    function openBatch() {
        batchVisible.value = true
    }

    function closeBatch() {
        file.value = undefined
        sameCards.value = []
    }

    function downloadTemplate() {
        downloadCsv('Template_SIM', [['cardNo', 'fee', 'expireIn']])
    }

    function downSameCardNos() {
        downloadCsv('same card', sameCards.value.map(item => [item.cardNo]))
    }

    function beforeUpload(e:File) {
        file.value = e
        return false
    }

    async function batchSubmit() {
        if(!file.value) {
            message.error(i18n.t('selectFileTips'))
            return
        }
        
        const rows = await readCsv(file.value)
        if(rows.length == 0) {
            return
        }

        if(rows.length > maxBatchCount) {
            message.error(i18n.t('maxUpload', [maxBatchCount]))
            return
        }

        const cards = rows.map(row => row.cardNo)
        let cardsSet = new Set(cards)
        if(cardsSet.size != cards.length) {
            message.error(i18n.t('cardNoRepeatTip'))
            return
        }

        rows.forEach(row => {
            row.expireIn = row.expireIn ? Math.floor((new Date(row.expireIn)).getTime() / 1000) : 0

            row.fee = row.fee ? Number(row.fee) : 0
            
        })

        const res = await saveBatchApi(rows)
        if(res.success) {
            batchVisible.value = false
            message.success(i18n.t('saveSuccess'))
            tableRef.value.load()
        }else {
            message.error(res.msg)
            if(res.code == 300) { //存在相同的
                sameCards.value = res.data
            }
        }
        
    }
    
    async function submit() {
        let {id, cardNo, fee, expireIn} = await formRef.value.validate()

        let params:any = {
            cardNo
        }
        if(id) {
            params.id = id
        }

        if(fee) {
            params.fee = Number(fee)
        }
        
        params.expireIn = expireIn ? expireIn.unix() : 0
        

        const res = await saveApi(params)
        if(res.success) {
            visible.value = false
            message.success(i18n.t('saveSuccess'))
            tableRef.value.load()
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }

    const columns = ref<Column[]>([
        {
            title : i18n.t('cardNo'),
            dataIndex : 'cardNo',
            align : 'center',
            inSearch : true,
        },

        {
            title : i18n.t('fee'),
            dataIndex : 'fee',
            align : 'center',
        },

        {
            title : i18n.t('expireDate'),
            dataIndex : 'expireIn',
            align : 'center',
            customRender({ record }) {
                return record.expireIn ?  parseTime(record.expireIn, '{y}-{m}-{d}') : ''
            }
        },

        {
            title : i18n.t('action'),
            dataIndex : '$action',
            align : 'center',
            $edit : resourceStore.hasPermission('iotSim:edit') ? (row) => {
                dialogTitle.value = i18n.t('edit')
                formFields.forEach(field => {
                    if(field.name == 'expireIn') {
                        field.defaultValue = row[field.name] ? dayjs(row[field.name] * 1000) : ''
                    }else {
                        field.defaultValue = row[field.name]
                    }
                    
                })

                visible.value = true
            } : undefined,

            $delete :  resourceStore.hasPermission('iotSim:delete') ? (async (row) => {
                const res = await deleteApi(row.id)
                if(res.success) {
                    message.success(i18n.t('deleteSuccess'))
                    tableRef.value.load()
                }else {
                    message.error(res.msg)
                }
            }) : undefined
        }
    ])
</script>

<style lang='scss' module>
    .username{
        display: inline-flex;
        align-items: center;
        gap: 10px;
    }
</style>